package com.example.search

import android.os.Bundle
import android.view.View

import androidx.activity.viewModels
import androidx.appcompat.widget.SearchView
import androidx.lifecycle.lifecycleScope

import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.entity.SimpleVideoEntity
import com.example.base.RouterPath
import com.example.common.mvi.BaseMviActivity
import com.example.search.adapter.KeyWordListAdapter
import com.example.search.adapter.SearchVideoListAdapter
import com.example.search.databinding.ActivitySearchBinding
import com.example.search.intent.SearchViewIntent
import com.example.search.state.SearchUiState
import com.example.search.vm.SearchViewModel
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = RouterPath.PATH_SEARCH_PAGE)
class SearchActivity : BaseMviActivity<ActivitySearchBinding>() {

    private val mViewModel:SearchViewModel by viewModels()

    //视频列表集合
    private val mVideoList = mutableListOf<SimpleVideoEntity>()

    //视频适配器
    private lateinit var mVideoListAdapter:SearchVideoListAdapter
    //热词搜索适配器
    private lateinit var mHotListAdapter:KeyWordListAdapter
    //历史记录适配器
    private lateinit var mHistoryListAdapter:KeyWordListAdapter


    @Autowired
    @JvmField
    var keyWords:String = ""

    private var pageIndex:Int = 1
    private var pageSize :Int = 10
    private var tempSearchKeyword: String = ""
    private var HotRecommentList = mutableListOf("蒙奇.D.路飞","波特卡斯.D.艾斯","萨博","罗罗诺亚.索隆","文斯莫克・山治","爱德华・纽盖特","好")

    private var HitToryList = mutableListOf<String>()

    override fun initViews() {

        ARouter.getInstance().inject(this)

        //视频列表
        mVideoListAdapter = SearchVideoListAdapter(mVideoList)
        mDatabinding.rvList.layoutManager = LinearLayoutManager(this@SearchActivity,LinearLayoutManager.VERTICAL,false)
        mDatabinding.rvList.adapter = mVideoListAdapter

        //搜索框文本事件监听
        mDatabinding.svKeywords.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                if(!query.isNullOrEmpty()){
                    mDatabinding.cltSearchKeywords.visibility = View.INVISIBLE
                    mDatabinding.rvList.visibility = View.VISIBLE
                    loadVideoByNewKeyword(query)
                }
                return false
            }
            override fun onQueryTextChange(newText: String?): Boolean {
                if (newText.isNullOrEmpty()) {
                    mDatabinding.cltSearchKeywords.visibility = View.INVISIBLE
                    mDatabinding.rvList.visibility = View.VISIBLE
                } else {
                    mDatabinding.cltSearchKeywords.visibility = View.VISIBLE
                    mDatabinding.rvList.visibility = View.INVISIBLE
                }
                return false
            }
        })

        //搜索热词
        mDatabinding.rvHotList.layoutManager = FlexboxLayoutManager(this@SearchActivity).apply {
            flexDirection = FlexDirection.ROW //水平方向
            flexWrap  = FlexWrap.WRAP //自动换行
            justifyContent = JustifyContent.FLEX_START //交叉轴在起点左侧
        }
        mHotListAdapter = KeyWordListAdapter(HotRecommentList)
        //设置热词搜索
        mHotListAdapter.setonItemClickener(object:KeyWordListAdapter.OnItemClickListener{
            override fun onItemChildclick(v: View?, position: Int) {
                mDatabinding.cltSearchKeywords.visibility = View.INVISIBLE
                mDatabinding.rvList.visibility = View.VISIBLE
                loadVideoByNewKeyword(HotRecommentList[position])
            }
        })
        mDatabinding.rvHotList.adapter = mHotListAdapter

        //历史记录
        val flex = FlexboxLayoutManager(this@SearchActivity)
        mDatabinding.rvHistoryList.layoutManager = flex
        flex.flexDirection = FlexDirection.ROW
        flex.flexWrap = FlexWrap.WRAP
        flex.justifyContent = JustifyContent.FLEX_START

        mHistoryListAdapter = KeyWordListAdapter(HitToryList)

        mHistoryListAdapter.setonItemClickener(object:KeyWordListAdapter.OnItemClickListener{
            override fun onItemChildclick(v: View?, position: Int) {
                mDatabinding.cltSearchKeywords.visibility = View.INVISIBLE
                mDatabinding.rvList.visibility = View.VISIBLE
                loadVideoByNewKeyword(HitToryList[position])
            }
        })
        mDatabinding.rvHistoryList.adapter = mHistoryListAdapter




    }
    private fun loadVideoByNewKeyword(keyword:String){
        //临时缓存一下关键词
        tempSearchKeyword = keyword
        //清空输入内容
        mDatabinding.svKeywords.setQuery("", false)
        //清理输入框焦点，关闭键盘
        mDatabinding.svKeywords.clearFocus()
        //发起数据请求
        lifecycleScope.launch {
            mViewModel.channel.send(SearchViewIntent.LoadSimpleVideoListByKeyword(keyword, pageIndex, pageSize))
        }
    }

    override fun getLayoutId(): Int=R.layout.activity_search

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(SearchViewIntent.LoadSimpleVideoListByKeyword(this.keyWords,this.pageIndex,this.pageSize))
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{

            when(it){
                is SearchUiState.LoadSimpleVideoSuccess->{
                    mVideoList.clear()
                    mVideoList.addAll(it.list)
                    mVideoListAdapter.notifyDataSetChanged()

                    //判断搜索有数据就缓存一下关键词
                    if (it.list.isNotEmpty() && tempSearchKeyword.isNotEmpty()){
                        //之前搜索过，先清理掉
                        if(HitToryList.indexOf(tempSearchKeyword) > -1){
                            HitToryList.remove(tempSearchKeyword)
                        }
                        //在集合第一个位置插入数据
                        HitToryList.add(0, tempSearchKeyword)

                        tempSearchKeyword = ""
                        mHistoryListAdapter.notifyDataSetChanged()
                    }

                }
                is SearchUiState.LoadSimpleVideoFail->{
                    showToast("没有搜索到关键词")
                }
                else->{}
            }
        }
    }
}